package com.ruoyi.mes.service.impl;

import java.util.List;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.mes.domain.MatPlanDetail;
import com.ruoyi.mes.domain.Material;
import com.ruoyi.mes.mapper.BuyOrdMapper;
import com.ruoyi.mes.mapper.MatPlanDetailMapper;
import com.ruoyi.mes.mapper.MaterialMapper;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mes.mapper.BuyNeedMapper;
import com.ruoyi.mes.domain.BuyNeed;
import com.ruoyi.mes.service.IBuyNeedService;

/**
 * 采购需求单Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-11
 */
@Service
public class BuyNeedServiceImpl implements IBuyNeedService {
    @Autowired
    private BuyNeedMapper buyNeedMapper;

    @Autowired
    private MatPlanDetailMapper matPlanDetailMapper;

    @Autowired
    private BuyOrdMapper buyOrdMapper;

    @Autowired
    private MaterialMapper materialMapper;

    /**
     * 查询采购需求单
     *
     * @param id 采购需求单主键
     * @return 采购需求单
     */
    @Override
    public BuyNeed selectBuyNeedById(Long id) {
        return buyNeedMapper.selectBuyNeedById(id);
    }

    /**
     * 查询采购需求单列表
     *
     * @param buyNeed 采购需求单
     * @return 采购需求单
     */
    @Override
    public List<BuyNeed> selectBuyNeedList(BuyNeed buyNeed) {
        return buyNeedMapper.selectBuyNeedList(buyNeed);
    }

    /**
     * 新增采购需求单
     *
     * @param buyNeed 采购需求单
     * @return 结果
     */
    @Override
    public int insertBuyNeed(BuyNeed buyNeed) {
        buyNeed.setCreateTime(DateUtils.getNowDate());
        return buyNeedMapper.insertBuyNeed(buyNeed);
    }

    /**
     * 修改采购需求单
     *
     * @param buyNeed 采购需求单
     * @return 结果
     */
    @Override
    public int updateBuyNeed(BuyNeed buyNeed) {
        return buyNeedMapper.updateBuyNeed(buyNeed);
    }

    /**
     * 批量删除采购需求单
     *
     * @param ids 需要删除的采购需求单主键
     * @return 结果
     */
    @Override
    public int deleteBuyNeedByIds(Long[] ids) {
        return buyNeedMapper.deleteBuyNeedByIds(ids);
    }

    /**
     * 删除采购需求单信息
     *
     * @param id 采购需求单主键
     * @return 结果
     */
    @Override
    public int deleteBuyNeedById(Long id) {
        return buyNeedMapper.deleteBuyNeedById(id);
    }

    /**
     * 获取生成采购订单-物料信息
     */
    @Override
    public AjaxResult selectBuyNeedByMtCode(String buyneedCode) {

        BuyNeed buyNeed = buyNeedMapper.selectBuyNeedByCode(buyneedCode);
        MatPlanDetail matPlanDetail = matPlanDetailMapper.selectMatPlanDetailByCodeName(buyNeed.getMatplanCode(), buyNeed.getMaterialName());

        Material material = materialMapper.selectMaterialByName(matPlanDetail.getMaterialName());
        matPlanDetail.setBuyNum(matPlanDetail.getNeedNum() - material.getMaterialNum());

        buyNeed.setStatus("已生成");
        buyNeedMapper.updateBuyNeed(buyNeed);
        return AjaxResult.success(matPlanDetail);
    }
}
